/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-11-27
 * Time: 15:53
 */


class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}


public class Main {
    public boolean evaluateTree(TreeNode root) {
        if (root.left == null) {
            return root.val == 1 ? true : false;
        }
        boolean leftRet = evaluateTree(root.left);
        boolean rightRet = evaluateTree(root.right);
        return root.val == 2 ? leftRet | rightRet : leftRet & rightRet;
    }

    public int sumNumbers(TreeNode root) {
        return dfs(root, 0);//根节点,前缀的和为0
    }

    public int dfs(TreeNode root, int preSum) {
        if (root == null) {
            return 0;
        }
        preSum = preSum * 10 + root.val;// 更新前缀和
        // 如果是叶子结点,直接返回更新后的前缀和
        if (root.left == null && root.right == null) {
            return preSum;
        }
        int ret = 0;
        // 计算左边的和
        if (root.left != null) {
            ret += dfs(root.left, preSum);
        }
        // 计算右边的和
        if (root.right != null) {
            ret += dfs(root.right, preSum);
        }
        return ret;
    }



}
